package com.test.test;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

public class DimenGenerator {

    private static final String[] SCREENS = {
            "values",
            "values-sw320dp", "values-sw480dp", "values-sw720dp",
//            "values-sw1080dp", "values-sw1920dp"
            "values-sw4320dp"  // 55寸4K广告屏
    };

    public static void generateFileAll() {
        String[] screens = DimenGenerator.SCREENS;
        for (String screen : screens) {
            DimenGenerator.generateFile(screen);
        }
    }

    public static void generateFile(String screen) {
        double scale = getScale(screen);

        File file = new File("build/res", screen);
        String absolutePath = file.getAbsolutePath();
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                mkdirs = file.mkdirs();
                if (!mkdirs) {
                    System.out.println("创建失败！" + absolutePath);
                    return;
                }
            }
        }
        System.out.println(absolutePath);

        String fileName = absolutePath + "/dimens.xml";
        generate("dp", 1000, fileName, scale);
        System.out.println("生成: " + screen);

        fileName = absolutePath + "/dimens_sp.xml";
        generate("sp", 120, fileName, scale);
    }


    private static void generate(String unit, int count, String fileName, double scale) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(fileName))) {
            writer.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>");

            for (int i = 1; i <= count; i++) {
                writer.printf("    <dimen name=\"%s_%d\">%.2f%s</dimen>%n", unit, i, i * scale, unit);
            }

            if (unit.equals("dp")) {
                for (int size : new int[]{1024, 1080, 1920}) {
                    writer.printf("    <dimen name=\"dp_%d\">%.2fdp</dimen>%n", size, size * scale);
                }
            }

            writer.println("</resources>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void generateDP(int dp) {
        for (String screen : SCREENS) {
            double scale = getScale(screen);
            System.out.printf("%s%n    <dimen name=\"dp_%d\">%.2fdp</dimen>%n", screen, dp, dp * scale);
        }
    }

    public static void generateSP(int sp) {
        for (String screen : SCREENS) {
            double scale = getScale(screen);
            System.out.printf("%s%n    <dimen name=\"sp_%d\">%.2fsp</dimen>%n", screen, sp, sp * scale);
        }
    }

    private static double getScale(String screen) {
        String valueName = screen.replaceAll("\\D", "");
        int width = 360;
        try {
            width = Integer.parseInt(valueName);
        } catch (Exception e) {

        }
        double scale = width / 360.0;
        return scale;
    }
}